var express = require('express');
var router = express.Router();
var connection = require('./connectDB');
router.post('*', async (req, res) => {
    var data = req.body;
    res.send(await fun2(data,req));
})
function fun2(data,req) {
    return new Promise((resolve, reject) => {
        connection.query('select * from userinfo where tel = ?', [data.tel], (err, results) => {
            if (results.length == 0) {
                if (req.url == '/telInfo' || req.url == '/psdInfo' || req.url == '/resetInfo') {
                    resolve({ code: 'no exist' });
                } else {
                    resolve(fun1(data));
                }
            } else {
                if (req.url == '/telInfo') {
                    resolve({ code: '200', userID: results });
                } else if (req.url == '/psdInfo') {
                    resolve(fun3(data))
                } else if (req.url == '/regInfo') {
                    resolve({ code: 'exist' });
                } else if (req.url == '/resetInfo') {
                    resolve(fun4(data));
                }
            }
        })
    })
}
function fun1(data) {
    return new Promise((resolve, reject) => {
        connection.query('insert into userinfo (tel,pwd) values (?,?)', [data.tel, data.password], (err, rows) => {
            if (err) {
                console.log('插入失败'+err)
            } else {
                resolve({ code: 'regsuccess' });
            }
        })
    })
}
function fun3(data) {
    return new Promise((resolve, reject) => {
        connection.query('select * from userinfo where tel = ? and pwd = ?', [data.tel, data.password], (err, rows) => {
            if (rows.length == 0) {
                resolve({ code: 'psderr' });
            } else {
                resolve({ code: '200', userID: rows });
            }
        })
    })
}
function fun4(data) {
    connection.query('update userinfo set pwd = ? where tel = ?', [data.password, data.tel], (err, rows) => {
        if (err) {
            console.log('更新失败')
        } else {
            resolve({ code: 'resetOK' });
        }
    })
}
module.exports = router;